<?php
/**
 * @Notes:【】
 * @Date: 2022-08-04 23:37
 */

namespace App\Service\Ocean;

use App\Dao\Ocean\OceanFishDao;
use App\Dao\Ocean\OceanUserFishDao;
use App\Dao\User\UserDao;
use App\Service\BaseService;
use App\Tool\Collect;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;

class OceanUserFishService extends BaseService
{

    /**
     * 成熟
     * @Inject()
     * @var OceanFishDao
     */
    protected $oceanFishDao;

    /**
     * @Inject()
     * @var OceanUserFishDao
     */
    protected $oceanUserFishDao;

    /**
     * @Inject()
     * @var UserDao
     */
    protected $userDao;


    public function lists(Collect $params)
    {
        $data = $this->oceanUserFishDao->lists($params);
        return $data;
    }

    public function add(Collect $params)
    {
        $res = $this->oceanFishDao->add($params);
        return $res;
    }

    public function edit($id, Collect $params)
    {
        $res = $this->oceanFishDao->edit($id, $params);
        return $res;
    }

    public function exchange($fish_id, $userId)
    {
        Db::beginTransaction();
        try {
            $exchange_power = 100;
            $oceanFish = $this->oceanFishDao->where('id', $fish_id)->firstOrError();
            $userDao = $this->userDao->where('user_id', $userId)->firstOrError();
            if ($userDao->fish_power < $exchange_power) {
                _Error('育苗不足');
            }
            $userDao->fish_power = 0;
            $userDao->save();
            $this->oceanUserFishDao->create([
                'price' => $oceanFish->price,
                'user_id' => $userId,
                'fish_id' => $fish_id,
                'grow_up_time' => time() + $oceanFish->grow_time
            ]);

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            _Error($e->getMessage());
        }
        return true;
    }

    public function sell($user_fish_id, $userId)
    {
        Db::beginTransaction();
        try {
            $oceanUserFishDao = $this->oceanUserFishDao
                ->where('id', $user_fish_id)
                ->lock(true)
                ->where('status', 1)
                ->where('user_id', $userId)
                ->firstOrError();
            $nowTime = time();
            if ($oceanUserFishDao->grow_up_time < $nowTime) {
                _Error('未成熟');
            }

            $oceanUserFishDao->status = 2;
            $oceanUserFishDao->save();
            $userDao = $this->userDao->where('uid', $userId)->firstOrError();
            $userDao->ocean_point = $oceanUserFishDao->price + $userDao->ocean_point;
            $userDao->ocean_power = 0;
            $userDao->save();
            Db::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            _Error($e->getMessage());
        }
        return true;
    }


}